<template>
  <div id="app">
    <div v-if="is_shown">
      <header id="header" class="auto-rem mui-bar mui-bar-nav mui-active">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
        <h1 class="mui-title">
          购物车
        </h1>
        <a class="mui-icon mui-icon-bars mui-pull-right"></a>
      </header>
      <div class="mui-content">
        <div id="shopscroll" class="mui-scroll-wrapper" style="bottom: 1.75rem;">
          <div class="mui-scroll" style="max-height: 100%; overflow-y: scroll">
            <cart-item v-if="carts.length > 0" :products="carts" @productChange="calcPrice" @cartsChange="changeCarts"></cart-item>
            <cart-item v-if="scorecarts.length > 0" :is_score_list=true :products="scorecarts" @productChange="calcPrice" @cartsChange="changeCarts"></cart-item>
          </div>
        </div>

      </div>
      <div class="bottom-nav-bar">
        <div class="left">
          <div class="left-button"></div>
          <div class="right-text">
          <span class="top-text">
            <template v-if="score > 0">积分: {{ (score / 100 * 10).toFixed(0)}}</template>
          </span>
            <span class="bottom-text">
            现金:
            <span class="price">￥{{((price + scoreprice) / 100).toFixed(2) }}</span>
          </span>
          </div>
          <span></span>
        </div>
        <div class="right" :class="{ unselect: confirmcarts.length === 0 }" @tap.prevent.stop="openConfirm">结算</div>
      </div>
    </div>
    <cart-confirm :confirmcarts="confirmcarts" :totalprice="price + scoreprice" :totalnum="totalnum" :totalscore="score" :opentime="opentime"></cart-confirm>
  </div>
</template>

<script>

import { ajax } from 'assets/js/Lib'
import { mask, maskSpinner } from 'assets/js/slgMask'
import { filter, groupBy } from 'lodash'

import CartItem from 'components/CartItem'
import CartConfirm from 'components/CartConfirm'

export default {
  data() {
    return {
      carts: [],
      scorecarts: [],
      confirmcarts: [],
      price: 0,
      score: 0,
      scoreprice: 0,
      totalnum: 0,
      opentime: 0,
      is_shown: false,
    }
  },
  components: {
    CartItem, CartConfirm
  },
  computed: {

  },
  //实例初始化最之前，无法获取到data里的数据
  beforeCreate() {
  },
  //在挂载开始之前被调用
  beforeMount() {
  },
  //已成功挂载，相当ready()
  mounted() {


    localStorage.setItem('$needloginpage', JSON.stringify({
      'id': 'shopcart',
      'url': 'shopcart.html'
    }))
    const vm = this

    mui.init({
      swipeBack: true,
      statusBarBackground: '#f7f7f7'
    })

//    mui('#shopscroll').scroll({
//      scrollY: true, //是否竖向滚动
//      scrollX: false, //是否横向滚动
//      startX: 0, //初始化时滚动至x
//      startY: 0, //初始化时滚动至y
//      indicators: false, //是否显示滚动条
//      deceleration: 0.0006, //阻尼系数,系数越小滑动越灵敏
//      bounce: true //是否启用回弹
//    });

    mask.show()
    document.querySelector('.mui-backdrop').appendChild(maskSpinner)

    let params = url('?');
    if (params && params.right_now && params.right_now == 1) {
      ajax({
        url: '/api/public/oauth_login',
        type: 'GET',
        data: {url: window.location.href},
        success: (res) => {
          console.log('oauth_login', res);
          if (res.url) {
            window.location.href = res.url;
          } else {
            ajax({
              url: '/api/product/detail',
              data: {id: params.product_id},
              type: 'GET',
              success: (res) => {
                // let product = res.product
                let product = res;
                let sku = null;
                for (let item of product.sku) {
                  if (item.id == params.sku_id) {
                    sku = item;
                    break;
                  }
                }
                this.confirmcarts = [{
                  id: null,
                  num: params.buynum,
                  check: false,
                  product_id: product.id,
                  product_name: product.name,
                  product_price: product.price,
                  product_old_price: product.old_price,
                  product_discount_price: product.discount_price,
                  savepath: product.file.savepath,
                  savename: product.file.savename,
                  is_score: product.is_score,
                  full_score_buy: product.full_score_buy,
                  sku_id: sku.id,
                  sku
                }];

                mask.close();
                console.log('this.confirmcarts', this.confirmcarts);
                this.totalnum = 0;
                this.confirmcarts.forEach(function(item) {
                  this.totalnum += item.num * 1
                }, this);
                this.opentime = new Date().getTime();
                this.price = sku.price * params.buynum;
                this.score = sku.discount_price * params.buynum;
                this.scoreprice = sku.old_price * params.buynum;
                this.totalnum = params.buynum;
                console.log('score', this.score);

                setTimeout(() => {
                  mui('.slg-cart-confirm').popover('show');
//                  this.is_shown = true;
                }, 500);
              }
            });

          }
        }
      });


    } else {
      ajax({
        url: '/api/cart/list',
        type: 'GET',
//        data: { userId: 58 },
        success: (res) => {
          const gourpres = groupBy(res, 'is_score')
          vm.carts = gourpres[0] || []
          vm.scorecarts = gourpres[1] || []

//        console.log('vm.carts', vm.carts);
//        console.log('vm.scorecarts', vm.scorecarts);

          mask.close()

          ajax({
            url: '/api/public/oauth_login',
            type: 'GET',
            data: {url: window.location.href},
            success: (res) => {
              console.log('oauth_login', res);
              if (res.url) {
                window.location.href = res.url;
              } else {
                this.is_shown = true;
              }
            }
          });
        }
      });
    }

  },
  //相关操作事件
  methods: {
    calcPrice: function (obj, is_score) {
      console.log('calcPrice', obj);
      let { score, price } = obj;
      if (is_score) {
        this.score = score
        this.scoreprice = price
      } else {
        this.price = price
      }
    },
    changeCarts: function(changes, is_score){
      console.log('changeCarts', changes);
      if (is_score) {
        this.scorecarts = changes
      } else {
        this.carts = changes
      }
      this.confirmcarts = filter(this.carts.concat(this.scorecarts), 'check')
    },
    openConfirm: function () {
      this.totalnum = 0
      this.confirmcarts.forEach(function(item) {
        this.totalnum += item.num * 1
      }, this);
      this.opentime = new Date().getTime()
      console.log('this.confirmcarts', this.confirmcarts);
      mui('.slg-cart-confirm').popover('show')
    }
  }
}
</script>

<style lang="less">
#app {
  .mui-content {
    padding-bottom: 2rem;
  }
}

.shop-cart {
  &.mui-card {
    margin: .3125rem 0;
    &:first-child {
      margin-top: .46875rem !important;
    }
  }

  .setting-button {
    opacity: .5;
    position: absolute;
    width: 2rem;
    right: 0;
    text-align: center;
    padding: .3333333rem 0;
  }

  .mui-card-header {
    font-size: .46875rem;
    line-height: .46875rem;
    padding: .3125rem .46875rem;
  }

  .mui-card-content {
    font-size: .4375rem;
    line-height: .4375rem;

    .mui-card-content-inner {
      padding: .5rem;
      padding-right: 0;
    }
  }
}

.bottom-nav-bar {
  width: 10rem;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  z-index: 2;
  overflow: hidden;
  &>div {
    float: left;
    height: 1.5625rem;
  }

  .left {
    width: 7rem;
    overflow: hidden;
  }

  .right {
    width: 3rem;
    color: #fff;
    font-size: .53125rem;
    font-weight: 500;
    background-color: #FF0036;
    line-height: 1.5625rem;
    text-align: center;
    &.unselect {
      background-color: #ccc;
      pointer-events: none;
    }
  }
}

.left-button {
  float: left;
}

.right-text {
  float: right;
  margin-right: .2rem;
  width: 5rem;
  &>span {
    width: 100%;
    display: block;
    text-align: right;
  }
  .top-text {
    font-size: .4rem;
    line-height: .4rem;
    height: .8rem;
    padding-top: .25rem;
    padding-bottom: .15rem;
  }
  .bottom-text {

    line-height: .8rem;
    font-size: .4rem;
    .price {
      color: #FF0036;
      font-size: .6rem;
    }
  }
}
</style>
